//获取权限方法
var userInfo = getAuthority();

var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};


layui.use(['layer', 'form', 'table', 'util', 'dtree','admin','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;
    var laypage = layui.laypage;

    var Authorization;//请求接口用
    var templateName = '';//枚举分组名称

    var selectedTemplate = {};//选中模板
    var idenTemplate = {//指标模板分页配置
        count:0,//总个数
        current:1,//当前页
        templateFistRenderPage:true,//指标模板是否第一次渲染分页
        list:[],//模板列表数据
    }
    var idenCofig = {//指标管理配置
        count:0,//总个数
        current:1,//当前页
        idenName:'',//指标名称
        fistRenderPage:true,//指标是否第一次渲染分页
        iden_type:'',//指标类型

        idenType : {},//指标类型
        procurementType:{},//获取渠道
        userType:{},//指标使用方式
        idenUnitsGroup:{},//单位分组
        microGroup:{},//枚举分组
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getTemplateIdenPower();
        getTemplateIdenManageTablePower();
        getIdentValuePower();
        getMicroTemplateList();
    }

    // 树形点击事件
    // dtree.on('node("treeTbTree")', function (obj) {
    //     var data = obj.param;
    //     layer.msg('你选择了：' + data.nodeId + '-' + data.context);
    //     // insTb.reload({where: {nodeId: data.nodeId}}, 'data');
    // });

    // 指标模板搜索按钮点击事件
    form.on('submit(searchTemplate)', function (data) {
        templateName = data.field.name;
        idenTemplate.templateFistRenderPage = true;
        getMicroTemplateList();
    });
    // 打开新增指标模板弹窗
    $('#addTemplateIdenBtn').click(function () {
        showTemplateIdenModel();
    });
    // 打开编辑指标模板弹窗
    $('#editTemplateIdenBtn').click(function () {
        if(selectedTemplate.hasOwnProperty("id")){
            showTemplateIdenModel(selectedTemplate);
        }else{
            layer.msg("请先选择模板", {icon: 2});
        }
    });
    //删除指标模板
    $('#deleteTemplateIdenBtn').click(function () {
        if(selectedTemplate.hasOwnProperty("id")){
            showDeleteTemplateIdenModel(selectedTemplate);
        }else{
            layer.msg("请先选择模板", {icon: 2});
        }
    });

    // 指标管理搜索按钮点击事件
    form.on('submit(filterIden)', function (data) {
        idenCofig.iden_type = '';
        idenCofig.idenName = data.field.iden_name;
        getIdenData()
    });
    //更多筛选点击
    $('#morefilter-btn-idenManage').click(function () {
        openMoreFilterModel();
        return false;
    })
    $(".layui-fluid .layui-card").click(function (node) {
        if(!(document.getElementById("idenMoreFilterModel").contains(node.target))){
            $("#idenMoreFilterModel").slideUp();
        }
    });
    // 指标管理更多筛选
    form.on('submit(idenMoreFilterModelSubmit)', function (data) {
        idenCofig.idenName = data.field.idenName;
        idenCofig.iden_type = data.field.iden_type;
        getIdenData();
        $("#idenMoreFilterModel").slideUp();
        return false;
    });
    $("#closeIdenMoreFilterModel").click(function () {
        $("#idenMoreFilterModel").slideUp();
    });
    $('#add-btn-template-idenManage').click(function () {
        openAddIdenManage();
    });
    $('#import-btn-template-idenManage').click(function () {
        openImportIdenManage();
    })

    // 表格工具条点击事件
    table.on('tool(identGroupTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showIdenManageEditModel(data);
        } else if (layEvent === 'delete') { // 删除
            showIdenManageDeleteModel(data);
        }
    });

    //查询条件class的加载和移除（适用于动态加载标签的情况--on事件需要jquery在1.6以上）
    $('#microTemplateListBox').on('click','ul li',function(e){
        var ul =  document.getElementById("microTemplateListBox");
        var item = e.target;
        var lists = Array.from(ul.querySelectorAll('li'));
        var index = lists.indexOf(item);
        selectedTemplate = idenTemplate.list[index];
        $(this).siblings().removeClass("active");
        $(this).addClass("active");
        getIdenOtherInfo();
        getIdenData();
    });

    form.on('select(idenType)', function(data){
        setAddIdentModelShowAndHidden(data.value);
    });

    /*渲染指标管理权限*/
    function getTemplateIdenPower() {
        var str = template("template-idenManage-tmpl",{});
        document.getElementById("template-idenManage-tmpl-box").innerHTML = str;
    }

    /*渲染分组表格里的权限*/
    function getTemplateIdenManageTablePower() {
        var str = template("ident-template-idenManage-tmp",{});
        document.getElementById("ident-template-idenManage-box").innerHTML = str;
    }

    /*渲染指标模板权限*/
    function getIdentValuePower() {
        var str = template("template-iden-tmpl",{});
        document.getElementById("template-iden-tmpl-box").innerHTML = str;
    }

    /*获取指标模板列表*/
    function getMicroTemplateList() {
        var req={
            current: idenTemplate.current,
            size: pageSize,
            name:templateName
        };
        axios.get(microUrl.template.queryList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    idenTemplate.list = data.records;
                    renderTemplateList(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    function renderTemplateList(data) {
        var str = template("microTemplateListTmpl",data);
        document.getElementById("microTemplateListBox").innerHTML = str;
        renderIdenTable({
            records:[],
            total:0
        });
        $("#microTemplateListBox ul li").eq(0).click();

        idenTemplate.count = data.total;
        //第一次才渲染分页
        if(idenTemplate.templateFistRenderPage){
            laypage.render({
                elem: 'templatePageBox'
                ,count: idenTemplate.count ,
                limit:pageSize,
                groups:1,
                current:idenTemplate.current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        idenTemplate.current = obj.curr;
                        idenTemplate.templateFistRenderPage = false;
                        getMicroTemplateList();
                    }
                }
            });
        }
    }

    /*获取指标数据*/
    function getIdenData() {
        var req={
            current: idenCofig.current,
            size: pageSize,
            iden_name:idenCofig.idenName,
            iden_type:idenCofig.iden_type,
            miid:selectedTemplate.id

        };
        axios.get(microUrl.iden.queryIden,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderIdenTable(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*渲染指标管理表格*/
    function renderIdenTable(data) {
        idenCofig.count = data.total;
        table.render({
            elem: '#identGroupTable',
            size: 'sm', //小尺寸的表格
            page: false,
            cellMinWidth: 100,
            data:data.records,
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'idenName', align: 'center', title: '指标名称'},
                {field: 'iden_type_name', align: 'center', title: '数据类型'},
                {field: 'idenSimpleName', align: 'center', title: '指标简称'},
                {field: 'isDisplayed', align: 'center', title: '是否展示',templet:function (d) {
                        return d.isDisplayed?"是":"否"
                    }},
                {field: 'isPk', align: 'center', title: '是否业务主键',templet:function (d) {
                        return d.isPk?"是":"否"
                    }},
                {field: 'isSearch', align: 'center', title: '是否可搜索',templet:function (d) {
                        return d.isSearch?"是":"否"
                    }},
                {field: 'status', align: 'center', title: '是否可用',templet:function (d) {
                        return d.status?"是":"否"
                    }},
                {field: 'memo', align: 'center', title: '描述'},
                {align: 'center', toolbar: '#ident-template-idenManage-box', title: '操作', minWidth: 120}
            ]]
        });

        idenCofig.count = data.total;
        //第一次才渲染分页
        if(idenCofig.fistRenderPage){
            laypage.render({
                elem: 'page-box'
                ,count: idenCofig.count,
                limit:pageSize,
                groups:1,
                current:idenCofig.current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        idenCofig.current = obj.curr;
                        idenCofig.fistRenderPage = false;
                        getIdenData();
                    }
                }
            });
        }
    }

    /*获取指标类型、获取渠道、使用方式*/
    function getIdenOtherInfo(){
        function getIdenType() {
            return axios.get(microUrl.iden.idenType,{
                params: {},
                headers:{
                    'Authorization':Authorization
                }
            })
        }
        function getProcurementType() {
            return axios.get(microUrl.iden.procurementType,{
                params: {},
                headers:{
                    'Authorization':Authorization
                }
            })
        }
        function getUserType() {
            return axios.get(microUrl.iden.userType,{
                params: {},
                headers:{
                    'Authorization':Authorization
                }
            })
        }
        //指标单位分组
        function getIdenUnitsGroup() {
            var req={
                current:1,
                size:1000
            };
            return axios.get(metadataUrl.unitsGroup.allUnitsGroup.unitsGroupList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
        }
        //枚举分组
        function getMicroGroup() {
            var req={
                current:1,
                size:1000
            };
            return axios.get(microUrl.group.queryList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
        }
        axios.all([getIdenType(), getProcurementType(),getUserType(),getIdenUnitsGroup(),getMicroGroup()])
            .then(axios.spread(function (idenType, procurementType,userType,idenUnitsGroup,microGroup) {
                // 两个请求现在都执行完成
                if(idenType.status == 200 &&idenType.data.message == "success") {
                    var data = idenType.data;
                    idenCofig.idenType = data;
                }
                if(procurementType.status == 200 &&procurementType.data.message == "success"){
                    var procurementTypeData = procurementType.data;
                    idenCofig.procurementType = procurementTypeData;
                }
                if(userType.status == 200 &&userType.data.message == "success"){
                    var userType = userType.data;
                    idenCofig.userType = userType;
                }
                if(idenUnitsGroup.status == 200 &&idenUnitsGroup.data.message == "success"){
                    var idenUnitsGroup = idenUnitsGroup.data.data;
                    idenCofig.idenUnitsGroup = idenUnitsGroup;
                }
                if(microGroup.status == 200 &&microGroup.data.message == "success"){
                    var microGroup = microGroup.data.data;
                    idenCofig.microGroup = microGroup;
                }

            }))
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*显示新增指标模板弹窗*/
    function showTemplateIdenModel(obj) {
        admin.open({
            type: 1,
            title: obj?'编辑指标模板':'新增指标模板',
            offset: "auto",
            content: $('#AddTemplateIdenModel').html(),
            success: function (layero, dIndex) {
                if(obj){//编辑
                    // 回显数据
                    form.val('AddTemplateIdenForm', obj);
                    // 表单提交事件
                    form.on('submit(AddTemplateSubmit)', function (data) {
                        layer.load(2);
                        var formData = new FormData();
                        formData.append('id',obj.id);
                        formData.append('name',data.field.name)
                        formData.append('sort',obj.sort)
                        formData.append('version',obj.version)
                        axios({
                            method: 'put',
                            url:microUrl.template.editTemplate,
                            data:formData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (res) {
                                if (res.status == 200 && res.data.message=="success") {
                                    layer.close(dIndex);
                                    layer.closeAll('loading');
                                    layer.msg("编辑成功", {icon: 1});
                                    getMicroTemplateList();
                                } else {
                                    layer.closeAll('loading');
                                    layer.msg(res.data.message, {icon: 2});
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            })
                        return false;
                    });
                }else{//新增
                    // 表单提交事件
                    form.on('submit(AddTemplateSubmit)', function (data) {
                        var formData = new FormData();
                        formData.append('name',data.field.name);
                        formData.append('sort',0);
                        axios({
                            method: 'POST',
                            url:microUrl.template.addTemplate,
                            data:formData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (response) {
                                if(response.status == 200 &&response.data.message == "success"){
                                    layer.close(dIndex);
                                    layer.closeAll('loading');
                                    layer.msg("新增成功", {icon: 1});
                                    current = 1;
                                    getMicroTemplateList();
                                }else{
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, { icon: 2 });
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            });

                        return false;
                    });
                }
            }
        });
    }

    /*显示删除指标模板弹窗*/
    function showDeleteTemplateIdenModel(obj) {
        layer.confirm('确定将永久删除指标模板“ '+obj.name+'”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:microUrl.template.deleteTemplate+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        getMicroTemplateList();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示编辑指标管理弹窗*/
    function showIdenManageEditModel(obj) {
        admin.open({
            type: 1,
            title: '编辑指标',
            offset: "auto",
            area: ['400px', '700px'],
            content: $('#model-edit-idenManage').html(),
            success: function (layero, dIndex) {
                var strObj = initOtherType();
                document.getElementById("editIdenTypeBox").innerHTML = strObj.idenType;
                document.getElementById("editProcurementTypeBox").innerHTML = strObj.procurementType;
                document.getElementById("editUseTypeBox").innerHTML = strObj.userType;
                document.getElementById("editIdenUnitsGroupBOX").innerHTML = strObj.idenUnitsGroup;
                document.getElementById("editIdentGroupBox").innerHTML = strObj.microGroup;
                $(".iden_precision,.identGroup,.ident_version,.idenUnitsGroup,.idenUnitsValue").hide();//默认数据类型为文本
                form.render('select');
                form.render('checkbox');
                form.on('select(idenType)', function(data){
                    if(data.value!=""){
                        setAddIdentModelShowAndHidden(data.value);
                    }
                });
                form.on('select(editIdenUnitsGroupBOX)', function(data){//指标单位分组
                    if(data.value!=""){
                        getIdenUnitSValue(data.value,function (str) {
                            document.getElementById("editIdenUnitsValueBOX").innerHTML = str;
                            form.render('select')
                        });
                    }
                });
                form.on('select(editIdentGroupBox)', function(data){//枚举分组下拉
                    if(data.value!="") {
                        getIdentGroupVersion(data.value, function (str) {
                            document.getElementById("edit_ident_version_box").innerHTML = str;
                            form.render('select')
                        });
                    }
                });
                var LowerCaseStrObjl = strAllReplaceLine(obj);

                if(LowerCaseStrObjl.iden_type){
                    setAddIdentModelShowAndHidden(LowerCaseStrObjl.iden_type);
                    if(LowerCaseStrObjl.iden_type==2){//数字
                        getIdenUnitSValue(LowerCaseStrObjl.iden_unit_name,function (str) {//初始指标单位名称
                            document.getElementById("editIdenUnitsValueBOX").innerHTML = str;
                            form.render('select')

                            // 回显数据
                            form.val('editIdenManageForm', LowerCaseStrObjl);
                        });
                    }else if(LowerCaseStrObjl.iden_type==4){//枚举
                        getIdentGroupVersion(LowerCaseStrObjl.identid, function (str) {//初始分组版本
                            document.getElementById("edit_ident_version_box").innerHTML = str;
                            form.render('select')

                            // 回显数据
                            form.val('editIdenManageForm', LowerCaseStrObjl);

                        });
                    }
                }

                // 回显数据
                form.val('editIdenManageForm', LowerCaseStrObjl);
                // 表单提交事件
                form.on('submit(editIdenSubmit)', function (data) {
                    switch (Number(data.field.iden_type)){
                        case 1:
                            if(data.field.iden_length==""){
                                layer.msg('请设置完整参数', {icon: 2});
                                return false;
                            }
                            break;
                        case 2:
                            if(data.field.iden_length==""||data.field.iden_unit_name==""||data.field.iden_unitvl_id==""){
                                layer.msg('请设置完整参数', {icon: 2});
                                return false;
                            }
                            break;
                        case 4:
                            if(data.field.identid==""||data.field.ident_version==""){
                                layer.msg('请设置完整参数', {icon: 2});
                                return false;
                            }
                            break;
                        default:
                            break;
                    }

                    var formData = new FormData();
                    formData.append('data_procurement',data.field.data_procurement);
                    formData.append('data_use',data.field.data_use);
                    formData.append('iden_alias_code',data.field.iden_alias_code||'');
                    formData.append('iden_name  ',data.field.iden_name  );
                    formData.append('iden_precision  ',data.field.iden_precision  );
                    formData.append('iden_simple_name ',data.field.iden_simple_name );
                    formData.append('iden_type ',data.field.iden_type );
                    formData.append('memo  ',data.field.memo  );
                    formData.append('mitid  ',selectedTemplate.id  );
                    formData.append('sort  ',0 );
                    formData.append('is_displayed',data.field.hasOwnProperty('is_displayed')?1:0 );
                    formData.append('is_pk',data.field.hasOwnProperty('is_pk')?1:0 );
                    formData.append('is_search ',data.field.hasOwnProperty('is_search')?1:0 );
                    formData.append('status',data.field.hasOwnProperty('status')?1:0 );
                    formData.append('id',obj.id);
                    formData.append('sort',obj.sort);
                    formData.append('version ',obj.version );

                    if(data.field.iden_type == 1){//文本
                        formData.append('iden_length ',data.field.iden_length );
                    }else if(data.field.iden_type == 2){//数字
                        formData.append('iden_length ',data.field.iden_length );
                        formData.append('iden_unit_name ',data.field.iden_unit_name );
                        formData.append('iden_unitvl_id  ',data.field.iden_unitvl_id  );
                    }else if(data.field.iden_type == 4){//枚举

                        formData.append('ident_version  ',data.field.ident_version  );
                        formData.append('identid  ',data.field.identid  );
                    }

                    axios({
                        method: 'put',
                        url:microUrl.iden.editIden,
                        data:formData,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg("编辑成功", {icon: 1});
                                getIdenData();
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        })
                    return false;
                });
            }
        });

    }

    /*将js对象属性名转换为下划线*/
    function strAllReplaceLine(new_obj){
        let arr = [];
        var result = strAllReplace(new_obj);
        return result;
        function strReplace(str) {
            const UP_CASE_REG =/[A-Z]/g;
            const NUMBER_REG=/[A-Za-z][\d]/g
            let newstr = ""
            getIndex(UP_CASE_REG, str)
            getIndex(NUMBER_REG, str)
            arr.sort((a,b)=> a-b )
            for(let i = 0;i < arr.length; i ++) {
                if(i === 0) {
                    newstr += str.slice(0,arr[i]) + "_"
                }
                else {
                    newstr += str.slice(arr[i-1],arr[i]) + "_"
                }
            }
            newstr += str.slice(arr[arr.length-1])
            return newstr.toLowerCase()
        }
        function getIndex(reg, str) {
            do{
                reg.test(str)
                if(reg.lastIndex !== 0 && reg.lastIndex-1 !== 0){//reg.lastIndex-1 !== 0判断首字母是否大写
                    arr.push(reg.lastIndex-1)
                }
            }while(reg.lastIndex > 0)
        }

        function strAllReplace(obj) {
            let newObj = {}
            Object.entries(obj).forEach(([key, value]) =>
            {
                newObj[strReplace(key)] = value
                arr = []
            })
            return newObj
        }
    }

    /*显示删除指标弹窗*/
    function showIdenManageDeleteModel(obj) {
        layer.confirm('确认删除吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1
        }, function (index) {
            layer.close(index);
            layer.load(2);
            axios({
                method: 'delete',
                url:microUrl.iden.deleteIden+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        getIdenData();
                        idenCofig.fistRenderPage = true;
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

    /*显示更多筛选框*/
    function openMoreFilterModel() {
        $("#idenMoreFilterModel").slideDown();
        var strObj = initOtherType();
        document.getElementById("searchIdenType").innerHTML = strObj.idenType;
        form.render('select');
    }
    /*显示新增指标弹窗*/
    function openAddIdenManage() {
        layui.use(['admin'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            admin.open({
                type: 1,
                title: '新增指标',
                offset: "auto",
                area: ['400px', '750px'],
                content: $('#model-add-idenManage').html(),
                success: function (layero, dIndex) {
                    var strObj = initOtherType();
                    document.getElementById("addIdenTypeBox").innerHTML = strObj.idenType;
                    document.getElementById("procurementTypeBox").innerHTML = strObj.procurementType;
                    document.getElementById("useTypeBox").innerHTML = strObj.userType;
                    document.getElementById("idenUnitsGroupBOX").innerHTML = strObj.idenUnitsGroup;
                    document.getElementById("identGroupBOX").innerHTML = strObj.microGroup;
                    $(".iden_precision,.identGroup,.ident_version,.idenUnitsGroup,.idenUnitsValue").hide();//默认数据类型为文本
                    form.render('select');
                    form.render('checkbox');
                    form.on('select(idenType)', function(data){
                        if(data.value!=""){
                            setAddIdentModelShowAndHidden(data.value);
                        }
                    });
                    form.on('select(idenUnitsGroupBOX)', function(data){
                        if(data.value!=""){
                            getIdenUnitSValue(data.value,function (str) {
                                document.getElementById("idenUnitsValueBOX").innerHTML = str;
                                form.render('select')
                            });
                        }
                    });
                    form.on('select(identGroup)', function(data){
                        if(data.value!=""){
                            getIdentGroupVersion(data.value,function(str){
                                document.getElementById("ident_version_box").innerHTML = str;
                                form.render('select')
                            });
                        }
                    });
                    // 表单提交事件
                    form.on('submit(addIdenSubmit)', function (data) {
                        switch (Number(data.field.iden_type)){
                            case 1:
                                if(data.field.iden_length==""){
                                    layer.msg('请设置完整参数', {icon: 2});
                                    return false;
                                }
                                break;
                            case 2:
                                if(data.field.iden_length==""||data.field.iden_unit_name==""||data.field.iden_unitvl_id==""){
                                    layer.msg('请设置完整参数', {icon: 2});
                                    return false;
                                }
                                break;
                            case 4:
                                if(data.field.identid==""||data.field.ident_version==""){
                                    layer.msg('请设置完整参数', {icon: 2});
                                    return false;
                                }
                                break;
                            default:
                                break;
                        }

                        var formData = new FormData();
                        formData.append('data_procurement',data.field.data_procurement);
                        formData.append('data_use',data.field.data_use);
                        formData.append('iden_alias_code',data.field.iden_alias_code||'');
                        formData.append('iden_name  ',data.field.iden_name  );
                        formData.append('iden_precision  ',data.field.iden_precision  );
                        formData.append('iden_simple_name ',data.field.iden_simple_name );
                        formData.append('iden_type ',data.field.iden_type );
                        formData.append('memo  ',data.field.memo  );
                        formData.append('mitid  ',selectedTemplate.id  );
                        formData.append('sort  ',0 );
                        formData.append('is_displayed',data.field.hasOwnProperty('is_displayed')?1:0 );
                        formData.append('is_pk',data.field.hasOwnProperty('is_pk')?1:0 );
                        formData.append('is_search ',data.field.hasOwnProperty('is_search')?1:0 );
                        formData.append('status',data.field.hasOwnProperty('status')?1:0 );

                        if(data.field.iden_type == 1){//文本
                            formData.append('iden_length ',data.field.iden_length );
                        }else if(data.field.iden_type == 2){//数字
                            formData.append('iden_length ',data.field.iden_length );
                            formData.append('iden_unit_name ',data.field.iden_unit_name );
                            formData.append('iden_unitvl_id  ',data.field.iden_unitvl_id  );
                        }else if(data.field.iden_type == 3){//日期
                            formData.append('iden_length ',255 );
                        }else if(data.field.iden_type == 4){//枚举
                            formData.append('ident_version  ',data.field.ident_version  );
                            formData.append('identid  ',data.field.identid  );
                            formData.append('iden_length ',255 );
                        }

                        axios({
                            method: 'POST',
                            url:microUrl.iden.addIden,
                            data:formData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (response) {
                                if(response.status == 200 &&response.data.message == "success"){
                                    layer.close(dIndex);
                                    layer.closeAll('loading');
                                    layer.msg("新增成功", {icon: 1});
                                    current = 1;
                                    getIdenData();
                                    idenCofig.fistRenderPage = true;
                                }else{
                                    layer.closeAll('loading');
                                    layer.msg(response.data.message, {icon: 2});
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                    // 进行重新登陆
                                    localStorage.clear();
                                    top.location.href=loginPageUrl;
                                }
                            });
                        return false;
                    });
                }
            });
        })

    }
    /*初始化指标用到的片段*/
    function initOtherType(){
        var strObj = {};
        strObj.idenType = template("template-idenType-tmpl",idenCofig.idenType);
        strObj.procurementType = template("template-procurementType-tmpl",idenCofig.procurementType);
        strObj.userType = template("template-userType-tmpl",idenCofig.userType);
        strObj.idenUnitsGroup = template("template-idenUnitsGroup-tmpl",idenCofig.idenUnitsGroup);
        strObj.microGroup = template("template-microGroup-tmpl",idenCofig.microGroup);

        return strObj;
    }

    /*设置新建指标显示隐藏项*/
    function setAddIdentModelShowAndHidden(type) {
        $(".iden_length,.iden_precision,.identGroup,.ident_version,.idenUnitsGroup,.idenUnitsValue").show();
        switch (Number(type)){
            case 1://文本
                $(".iden_precision,.identGroup,.ident_version,.idenUnitsGroup,.idenUnitsValue").hide();
                break;
            case 2://数字
                $(".identGroup,.ident_version").hide();
                break;
            case 3://日期
                $(".iden_length,.iden_precision,.identGroup,.ident_version,.idenUnitsGroup,.idenUnitsValue").hide();
                $("#iden_length input").val(255);
                break;
            case 4://枚举
                $(".iden_length,.iden_precision,.idenUnitsGroup,.idenUnitsValue").hide();
                $("#iden_length input").val(255);
                break;
            default:
                break;
        }
    }

    function getIdenUnitSValue(group,callback) {
        var req={
            current : 1,
            size: 1000,
            parid:group
        };
        axios.get(metadataUrl.unitsGroup.idenData.idenDataList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var str = template("template-idenUnitsValue-tmpl",data);
                    callback(str);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    
    function getIdentGroupVersion(gid,callback) {
        axios.get(microUrl.version.queryVersion+gid,{
            params: {},
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data;
                    var str = template("template-microValue-tmpl",data);
                    callback(str);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*显示导入指标弹窗*/
    function openImportIdenManage() {
        admin.open({
            title: '导入指标',
            url: 'template/importIden.html',
            // offset: "auto",
            end: function () {

            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }

});


